package com.mooral.bean;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mooral.context.Context;
import com.mooral.context.ContextSession;
import com.mooral.dataAccess.DataAccessConnection;

public class Beans extends ArrayList<Bean> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7676194496623529750L;

	
	 public void populate(Bean bean, ResultSet resultSet) throws SQLException {
		  while (resultSet.next()) {
			  Bean nBean = (Bean)bean.clone();
			  nBean.populate(resultSet);
			  add(nBean);
		  }
	 }
	 

	 public int getCount (String completeSql) throws Exception {
		 String sql = "";
		 String[] tmp = completeSql.toLowerCase().split("from");
		 
		 String[] tmp1 = tmp[1].toLowerCase().split("limit");
		 sql = "select count(1) from " + tmp1[0];

		 
		Context context = ContextSession.getCurrentContext();
		DataAccessConnection dataAccessConnection = context.getDataAccessConnection();
		ResultSet resultSet = dataAccessConnection.getResultSetQuery(sql);
		resultSet.next();
		int listSize = resultSet.getInt(1);
		dataAccessConnection.disposeConnection();
		return listSize;
	 }
	 
	/* 
		resultSet = dataAccessConnection.getResultSetQuery(merchants.getCountSql(sql));
		resultSet.next();
		int listSize = resultSet.getInt(1);
*/
	 
	 /**
	  * Sobrecargo el metodo para soportar un query
	  * @param bean
	  * @param query
	  * @throws Exception
	  */
	 public void populate(Bean bean, String query) throws Exception {
		 
		Context context = new Context();
		 
		DataAccessConnection dataAccessConnection = context.getDataAccessConnection();
		ResultSet resultSet = dataAccessConnection.getResultSetQuery(query);
		 
		this.populate(bean, resultSet);
		
		dataAccessConnection.disposeConnection();
	 }
	 
}